import { Base64 } from 'js-base64'

const { export_json_to_excel, export_json_to_excel_mul_Sheet, download_excel_by_id, download_excel_by_url } = require('./excel/Export2Excel');

// 导出excel
export const exportJson2Excel = export_json_to_excel;
// 多sheet导出
export const exportJson2ExcelMulSheet = export_json_to_excel_mul_Sheet;

export const downloadExcelByUrl = download_excel_by_url;

export const downloadExcelById = download_excel_by_id;

export const formatJson = (filterVal, jsonData) => {
    return jsonData.map(v => filterVal.map(j => v[j]));
}

// 获取cookie
export const getCookie = c_name => {
    if (document.cookie.length>0){
        let c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1){
            c_start=c_start + c_name.length+1
            let c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return ""
}
// 获取用户角色
export const getUserRole = () => {
    const userRole = localStorage.getItem('currentRole') && JSON.parse(localStorage.getItem('currentRole')) || {};
    return userRole
};
// 获取用户信息
export const getUserInfo = () => {
    const userInfo = localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')) || {};
    return userInfo
};
export const clearCookie=(name)=> {
    setCookie(name, "", -1);
}

// 登录校验
export const checkLogin = () => {
    const tokenUUMS = getCookie('Sw.WorkLine.Http.Api');
    return tokenUUMS;
};
/**
 * 设置localStorage
 */
export const setStore = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);

    }
    window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStore = (name) => {
    if (!name) return;
    return  JSON.parse(JSON.stringify(window.localStorage.getItem(name)));

}

// 数字加,号分隔格式化
export const formatNum = (num,counts, mark) => {
    mark = mark || ',';
    counts = counts || 3;
    num = num.toString().split(".");
    var tempAry = num[0].split("").reverse();
    var res=[];
    for(var i=0,len=tempAry.length;i<len;i++){
        if(i%counts===0&&i!==0){
            res.push(mark);
        }
        res.push(tempAry[i]);
    }
    res.reverse();
    if(num[1]){
        res=res.join("").concat("."+num[1]);
    }else{
        res=res.join("");
    }
    return res;
}

// 单位转换成万
export const transUnit2Wan = (value, formatCounts, formatMark) => {
    let res = value >= 10000 ? (value / 10000).toFixed(2) + '万' : value.toFixed(2);
    return formatCounts ? formatNum(res, formatCounts, formatMark || ',' ) : res;
}

// 深度复制
export const deepClone = o => {
    // 判断如果不是引用类型，直接返回数据即可
    if (typeof o === 'string' || typeof o === 'number' || typeof o === 'boolean' || typeof o === 'undefined') {
        return o
    } else if (Array.isArray(o)) { // 如果是数组，则定义一个新数组，完成复制后返回
        // 注意，这里判断数组不能用typeof，因为typeof Array 返回的是object
        console.log(typeof [])  // --> object
        var _arr = []
        o.forEach(item => { _arr.push(item) })
        return _arr
    } else if (typeof o === 'object') {
        var _o = {}
        for (let key in o) {
            _o[key] = deepClone(o[key])
        }
        return _o
    }
};

/**
 * 设置cookie
 */
export function setCookie(name, value, hours = 24) {
    let str = name + "=" + value;
    const time = new Date(new Date().getTime() + hours * 3600 * 1000).toGMTString();  // toGMTstring将时间转换成字符串
    str += "; expires=" + time;
    // 写入Cookie
    document.cookie = str;
}

//ip验证
export function validateIP(value) {
  if(value==''||value==undefined||value==null){
    return false;
  }else {
    const reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    if ((!reg.test(value)) && value != '') {
      return false;
    } else {
      return true;
    }
  }
}

export function getYourIP() {
    var clientIp = '';
    var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
    if (RTCPeerConnection) (function () {
        var rtc = new RTCPeerConnection({iceServers: []});
        if (1 || window.mozRTCPeerConnection) {
            rtc.createDataChannel('', {reliable: false});
        }
        ;

        rtc.onicecandidate = function (evt) {
            if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
        };
        rtc.createOffer(function (offerDesc) {
            grepSDP(offerDesc.sdp);
            rtc.setLocalDescription(offerDesc);
        }, function (e) {
            console.warn("offer failed", e);
        });


        var addrs = Object.create(null);
        addrs["0.0.0.0"] = false;

        function updateDisplay(newAddr) {
            if (newAddr in addrs) return;
            else addrs[newAddr] = true;
            var displayAddrs = Object.keys(addrs).filter(function (k) {
                return addrs[k];
            });
            for (var i = 0; i < displayAddrs.length; i++) {
                if (displayAddrs[i].length > 16) {
                    displayAddrs.splice(i, 1);
                    i--;
                }
            }
            console.log(displayAddrs[0],'__________ip地址__________');
            setStore('clientIp',displayAddrs[0])
        }

        function grepSDP(sdp) {
            var hosts = [];
            sdp.split('\r\n').forEach(function (line, index, arr) {
                if (~line.indexOf("a=candidate")) {
                    var parts = line.split(' '),
                      addr = parts[4],
                      type = parts[7];
                    if (type === 'host') updateDisplay(addr);
                } else if (~line.indexOf("c=")) {
                    var parts = line.split(' '),
                      addr = parts[2];
                    updateDisplay(addr);
                }
            });
        }
        return clientIp;
    })();
    else {
        console.log("请使用主流浏览器：chrome,firefox,opera,safari");
        setStore('clientIp','0.0.0.0')
    }
}